﻿#region Using Directives

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

#endregion Using Directives


namespace Edinger.Controls
{
    internal sealed class TextEditorDocument
    {
        #region Fields

        private Stream stream;
        private IList<long> lineOffsets;
        private byte[] buffer;

        #endregion Fields


        #region Methods

        public string GetLine(int line)
        {
            long lineOffset = lineOffsets[line];
            long nextLineOffset = lineOffsets[line + 1];
            int lineLength = (int)(nextLineOffset - lineOffset);
            if (buffer.Length < lineLength)
                this.buffer = new byte[lineLength];

            stream.Seek(lineOffset, SeekOrigin.Begin);
            stream.Read(buffer, 0, lineLength);

            string text = Encoding.UTF8.GetString(buffer, 0, lineLength);

            return text.TrimEnd('\r', '\n');
        }

        #endregion Methods


        #region Properties

        public int LineCount
        {
            get
            {
                return lineOffsets.Count - 1;
            }
        }

        #endregion Properties


        #region Constructors

        public TextEditorDocument(Stream stream, IList<long> lineOffsets)
        {
            this.stream = stream;
            this.lineOffsets = lineOffsets;
            this.buffer = new byte[1024 * 8];
        }

        #endregion Constructors
    }
}
